﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class Accounts : System.Web.UI.Page
{
    CSMSWebService.CSMSWebService csms = new CSMSWebService.CSMSWebService();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!this.IsPostBack)
            {
                Session["searchAccounts"] = false;
                try
                {
                    loadData();
                    ViewState["gv"] = gvAccounts.DataSource;
                    ViewState["SortDirection"] = "DESC";
                }
                catch (System.Exception ex)
                {
                    Response.Write("<script>alert('" + "LoadDB failed" + "')</script>");
                }
                btnSave.Visible = false;
                btnNew.Visible = true;
                btnAdd.Visible = true;

            }

            gvAccounts.DataSource = ViewState["gv"];
            gvAccounts.DataBind();

            if ((bool)Session["searchAccounts"])
            {
                btnSave.Visible = true;
                btnNew.Visible = true;
                btnAdd.Visible = false;
            }
            else
            {
                btnSave.Visible = false;
                btnNew.Visible = true;
                btnAdd.Visible = true;
            }
            btnSave.Attributes.Add("onclick", "if(!confirm('Are you sure?')) return false;");
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Some thing wrong!" + "')</script>");
        }
       
    }

    protected void loadData(){
        try
        {
            loadDdlRole();
            DataTable dt = new DataTable();
            List<CSMSWebService.Account> listAcc = csms.GetListAccount().ToList();
            dt.Columns.Add("Account ID");
            dt.Columns.Add("Username");
            dt.Columns.Add("Password");
            dt.Columns.Add("Role");
            dt.Columns.Add("isActive");
            foreach (CSMSWebService.Account item in listAcc)
	        {
                string role = "";
                for (int i = 0; i < ddlRole.Items.Count; i++)
                {
                    if (int.Parse(ddlRole.Items[i].Value) == item.roleId)
                        role = ddlRole.Items[i].Text;
                }
                dt.Rows.Add(item.accId, item.username, item.password, role, item.isActive);
	        }

            gvAccounts.DataSource = dt;
            gvAccounts.AutoGenerateSelectButton = true;
            gvAccounts.AllowPaging = true;
            gvAccounts.PageSize = 3;
            gvAccounts.DataBind();
            ViewState["gv"] = gvAccounts.DataSource;
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Load failed" + "')</script>");
            Response.Redirect("404.aspx");
        }
    }
    protected void clear(){
        txtAccountID.Text = null;
        txtUsername.Text = null;
        txtPassword.Text = null;
        txtSearch.Text = null;
        txtSearch.Enabled = true;
        btnSearch.Enabled = true;
        ddlSearchBy.Enabled = true;
        loadData();
    }

    protected void loadDdlRole()
    {
        try
        {
            DataTable dtDdl = new DataTable();
            List<CSMSWebService.Role> listRole = csms.GetListRole().ToList();
            dtDdl.Columns.Add("RoleID");
            dtDdl.Columns.Add("RoleName");
            foreach (CSMSWebService.Role item in listRole)
            {
                dtDdl.Rows.Add(item.roleId, item.roleName);
            }
            ddlRole.DataSource = dtDdl;
            ddlRole.DataValueField = "RoleID";
            ddlRole.DataTextField = "RoleName";
            ddlRole.DataBind();
        }
        catch (Exception)
        {

        }
    }


    protected void addNewAccount()
    {
        try
        {
            CSMSWebService.Account acc = new CSMSWebService.Account();
            acc.username = txtUsername.Text;
            acc.password = txtPassword.Text;
            acc.roleId = int.Parse(ddlRole.SelectedValue);
            acc.isActive = chkIsActive.Checked;
            csms.AddNewAccount(acc);
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Add failed" + "')</script>");
        }
        finally
        {
            loadData();
            clear();
        }
    }

    //protected void updateAccount()
    //{
    //    try
    //    {
    //        CSMSWebService.Account cate = new CSMSWebService.Account();
    //        cate.AccountId = int.Parse(txtAccountID.Text);
    //        cate.AccountName = txtAccountName.Text;
    //        cate.description = txtPassword.Text;
    //        csms.UpdateAccount(int.Parse(txtAccountID.Text), cate);
    //    }
    //    catch (System.Exception ex)
    //    {
    //        Response.Write("<script>alert('" + "Update failed" + "')</script>");
    //    }
    //    finally
    //    {            
    //        loadData();
    //        clear();
    //    }
    //}
    //protected void deleteAccount()
    //{
    //    try
    //    {
    //        CSMSWebService.Account cate = new CSMSWebService.Account();
    //        cate.AccountId = int.Parse(txtAccountID.Text);
    //        cate.AccountName = txtAccountName.Text;
    //        cate.description = txtPassword.Text;
    //        csms.DeleteAccount(int.Parse(txtAccountID.Text));
    //        loadData();
    //    }
    //    catch (System.Exception ex)
    //    {
    //        Response.Write("<script>alert('" + "Delete failed" + "')</script>");
    //    }
    //    finally
    //    {
    //        clear();
    //    }

    //}

    protected void searchBy()
    {
        DataTable dtTmp;
        DataView dv;
        try
        {
            loadData();
            dtTmp = (DataTable) gvAccounts.DataSource;
            #region searchmethod
            if (ddlSearchBy.Text.Equals("ID"))
            {
                gvAccounts.AutoGenerateSelectButton = true;
                gvAccounts.AllowPaging = true;
                gvAccounts.PageSize = 3; ;
                dv = new DataView(dtTmp);
                dv.RowFilter = string.Format("[Account ID] = {0}", int.Parse(txtSearch.Text.Trim()));
                gvAccounts.DataSource = dv;
                gvAccounts.DataBind();
            }
            if (ddlSearchBy.Text.Equals("Account Name"))
            {
                gvAccounts.AutoGenerateSelectButton = true;
                gvAccounts.AllowPaging = true;
                gvAccounts.PageSize = 3;
                dv = new DataView(dtTmp);
                dv.RowFilter = string.Format("[Account Name] LIKE '%{0}%'", txtSearch.Text.Trim());
                gvAccounts.DataSource = dv;
                gvAccounts.DataBind();
            }
            if (ddlSearchBy.Text.Equals("Description"))
            {
                gvAccounts.AutoGenerateSelectButton = true;
                gvAccounts.AllowPaging = true;
                gvAccounts.PageSize = 3;
                dv = new DataView(dtTmp);
                dv.RowFilter = string.Format("[Description] LIKE '%{0}%'", txtSearch.Text.Trim());
                gvAccounts.DataSource = dv;
                gvAccounts.DataBind();
            }
            ViewState["gv"] = ((DataView)gvAccounts.DataSource).ToTable();
#endregion
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Search failed" + "')</script>");
        }
        finally
        {
            Session["searchAccounts"] = true;
        }
        
    }

    protected void gvAccounts_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            GridViewRow r = gvAccounts.SelectedRow;
            txtAccountID.Text = Server.HtmlDecode(r.Cells[1].Text);
            txtUsername.Text = Server.HtmlDecode(r.Cells[2].Text);
            txtPassword.Text = Server.HtmlDecode(r.Cells[3].Text);
            btnSave.Visible = true;
            btnNew.Visible = true;
            btnAdd.Visible = false;
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Selected index changing failed" + "')</script>");
        }
        
    }
    protected void gvAccounts_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            gvAccounts.PageIndex = e.NewPageIndex;
            gvAccounts.DataSource = ViewState["gv"];
            gvAccounts.DataBind();

            txtAccountID.Text = null;
            txtUsername.Text = null;
            txtPassword.Text = null;
            txtSearch.Text = null;
            txtSearch.Enabled = true;
            btnSearch.Enabled = true;
            ddlSearchBy.Enabled = true;

            btnSave.Visible = false;
            btnNew.Visible = true;
            btnAdd.Visible = true;
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Page index changing failed" + "')</script>");
        }
        
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        clear();
        loadData();
        
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //insertAccount();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        //updateAccount();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        //deleteAccount();
    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        searchBy();
    }
    protected void btnReload_Click(object sender, EventArgs e)
    {
        clear();
        loadData();
    }
    protected void gvAccounts_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            DataTable dataTable = ViewState["gv"] as DataTable;

            if (dataTable != null)
            {
                DataView dataView = new DataView(dataTable);
                if (ViewState["SortDirection"].ToString().Trim().Equals("ASC"))
                {
                    dataView.Sort = e.SortExpression + " " + "DESC";
                    ViewState["SortDirection"] = "DESC";
                }
                else
                {
                    dataView.Sort = e.SortExpression + " " + "ASC";
                    ViewState["SortDirection"] = "ASC";
                }
                gvAccounts.DataSource = dataView;
                gvAccounts.DataBind();
                ViewState["gv"] = dataView.ToTable();
            }        
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Sort failed" + "')</script>");
        }
        
    }
    
   
}
